import React, { useMemo, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { Input, Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import styles from './index.module.less';
import AppRouter from '../../router/AppRouter';

interface IProps {
    routes: Routes[],
}
const { Search } = Input;

const treeData: DataNode[] = [
    {
        title: 'DEMOS',
        key: '0-0',
        selectable: false,
        children: [
            {
                title: 'demo',
                key: '/demos/demo',
            },
            {
                title: 'icon',
                key: '/demos/icon',
            },
            {
                title: '文件预览',
                key: '/demos/fileView',
            },
        ],
    },
    {
        title: '全局事件总线',
        key: '/demos/mitt',
    },
    {
        title: 'React Hooks',
        key: '0-3',
        selectable: false,
        children: [
            {
                title: 'UseRef',
                key: '/demos/useref',
            },
            {
                title: 'UseImperativeHandle',
                key: '/demos/imperativeHandle',
            },
        ],
    },
];

const DemoManagement = (props: IProps) => {
    const { routes } = props;
    const history = useHistory();

    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
    const [searchValue, setSearchValue] = useState('');
    const [autoExpandParent, setAutoExpandParent] = useState(true);

    const onExpand = (newExpandedKeys: React.Key[]) => {
        console.log(newExpandedKeys, 'newExpandedKeys');
        setExpandedKeys(newExpandedKeys);
        setAutoExpandParent(false);
    };

    const getParentKey = (key: React.Key, tree: DataNode[]): React.Key => {
        let parentKey: React.Key;
        for (let i = 0; i < tree.length; i++) {
            const node = tree[i];
            if (node.children) {
                if (node.children.some(item => item.key === key)) {
                    parentKey = node.key;
                } else if (getParentKey(key, node.children)) {
                    parentKey = getParentKey(key, node.children);
                }
            }
        }
        return parentKey!;
    };

    const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { value } = e.target;
        setSearchValue(value);
        setAutoExpandParent(true);
    };

    const onSelect = (selectedKeysValue: React.Key[], info: any) => {
        console.log('onSelect', selectedKeysValue, info);
        if (!info.node.children) {
            history.push(selectedKeysValue[0]);
        }
    };

    const treeDataSearch = useMemo(() => {
        const loop = (data: DataNode[]): DataNode[] =>
            data.map(item => {
                const strTitle = item.title as string;
                const index = strTitle.indexOf(searchValue);
                const beforeStr = strTitle.substring(0, index);
                const afterStr = strTitle.slice(index + searchValue.length);
                const title =
                    index > -1 ? (
                        <span>
                            {beforeStr}
                            <span className="site-tree-search-value">{searchValue}</span>
                            {afterStr}
                        </span>
                    ) : (
                        <span>{strTitle}</span>
                    );
                if (item.children) {
                    return { title, key: item.key, children: loop(item.children) };
                }

                return {
                    title,
                    key: item.key,
                };
            });

        return loop(treeData);
    }, [searchValue]);

    return (
        <div className={styles['demo-management']}>
            <div className={styles['tree-menu']}>
                <Search style={{ marginBottom: 8 }} placeholder="Search" onChange={onChange} />
                <Tree
                    onExpand={onExpand}
                    onSelect={onSelect}
                    expandedKeys={expandedKeys}
                    autoExpandParent={autoExpandParent}
                    treeData={treeDataSearch}
                    showLine
                />
            </div>
            <AppRouter routes={routes}></AppRouter>
        </div>
    );
};

export default DemoManagement;